package com.whq.thrift.api.bs.demo01.bs_account.add;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.whq.common.StringUtil;
import com.whq.thrift.api.common.constants.CommonConfigConstants;
import com.whq.thrift.api.common.constants.CommonErrorCodeConstants;
import com.whq.thrift.api.common.thriftclient.AbstractApiJsonCallback;
import com.whq.thrift.api.common.thriftclient.InvokeThriftStatus;
import com.whq.thrift.api.common.thriftserver.ResponseBase;
import com.whq.thrift.api.thrift.bs.service.service.ApiDetailInterface;
import com.whq.thrift.api.thrift.bs.service.service.BsBaseSpringService;

public class ApiDetailImpl implements ApiDetailInterface {
	private static final Logger LOGGER = LoggerFactory.getLogger(ApiDetailImpl.class);

	public ResponseBase execApi(BsBaseSpringService bsBaseSpringService, String method, Map<String, String> params, Map<String, String> ctx) {
		String name = params.get("name");
		if (StringUtil.isBlank(name)) {
			return new ResponseBase(CommonErrorCodeConstants.ERR_CODE_LACK_PARAM, "缺少参数：name");
		}
		
		
		Map<String, String> parameters = new HashMap<String, String>(0);
		parameters.put(CommonConfigConstants.THRIFT_PARAM_METHOD, "account.add");
		parameters.put("name", name);

		final InvokeThriftStatus invokeThriftStatus = new InvokeThriftStatus();
		invokeThriftStatus.setComplete(false);
		invokeThriftStatus.setInvokingMethod(parameters.get(CommonConfigConstants.THRIFT_PARAM_METHOD));

		// 异步调用
		bsBaseSpringService.asyncInvokeThriftService(method, new AbstractApiJsonCallback() {
			@Override
			public void doResponseApiJson(String response) {
				try {
					ResponseBase responseBase = JSON.parseObject(response, ResponseBase.class);
					invokeThriftStatus.setResponseObj(responseBase);
				} catch (Exception e) {
					LOGGER.error("parse [" + response + "] to ResponseBase exception: ", e);
					invokeThriftStatus.setResponseObj(new ResponseBase(CommonErrorCodeConstants.ERR_CODE_PARSE_RESPONSE_ERROR, "解析 account.add 接口返回结果出错"));
				}

				invokeThriftStatus.setComplete(true);
			}
		}, "as-demo01", parameters, ctx, 1000);

		// 1000毫秒超时判断
		for (int i = 0; i < 1000; i++) {
			if (invokeThriftStatus.isComplete()) {
				break;
			}
			try {
				Thread.sleep(1);
			} catch (Exception e) {

			}
		}

		if (invokeThriftStatus.isComplete()) {
			return invokeThriftStatus.getResponseObj();
		} else {
			return new ResponseBase(CommonErrorCodeConstants.ERR_CODE_INVOKE_THRIFT_SERVICE_TIMEOUT,
					"调用Thrift接口[" + invokeThriftStatus.getInvokingMethod() + "]超时");
		}
	}

}
